<?php
/**
 * 奖励管理
 */
class jiangli2Action extends baseAction
{

    public function _initialize() {
        parent::_initialize();
        $this->_mod = D('jiangli_log');
        $this->_user = D('user');
        $this->_order = D('item_orders');
    }

	public function index(){
        $Order = new OrderModel();
        //本月时间间隔
        $st =date('Y-m-01', strtotime(date("Y-m-d")));
        $et = date('Y-m-d', strtotime("$st +1 month -1 day"));
        $month = date('Y-m', $st);

        $users = $this->_user->field("id")->select();
        foreach($users as $u) {
            $rebate = $Order->getUserRebate($u['id'], $st, $et);
            $shouru = $rebate[0]['award'] + $rebate[1]['award'];
            if($shouru > 0){
                $data = array(
                    'uid' => $u['id'],
                    'shouru' => $shouru,
                    'status' => '0',
                    'type' => '1',
                    's0time' => NOW_TIME,
                    'month' => $month,
                );

                $this->_mod->add($data);
            }
        }

        $this->show('start');
	}
	//计算当月销售额
	public function getCount($page = 0){
		$BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
		$LastDay = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
		$end_day = date('d', $LastDay);
		$t = time();
		$s_t = mktime(0,0,0,date('m',$t),1,date('Y',$t));
		$e_t = mktime(23,59,59,date('m',$t),$end_day,date('Y',$t));
		$page = $page?$page-1:0;
		$p1 = $page * 10;
		
		$u_list = $this->_user->limit("$p1, 10")->select();
		foreach($u_list as $v){
			$q_count = $this->jisuan($v['id'], $s_t, $e_t, '汽车');
			$j_count = $this->jisuan($v['id'], $s_t, $e_t, '建筑');
			
			$data = array(
				'uid' => $v['id'],
				'shouru' => $q_count + $j_count,
				'status' => '0',
				'type' => '1',
				's0time' => time()
			);
			if($q_count + $j_count){
				$this->_mod->add($data);
			}
		}
	}
	
	private function jisuan($uid, $s_t, $e_t, $cate){
		$utype = M('usertype');
		$where = array(
			'uid' => $uid,
			'status' => 4,
			'cate' => array('like', "$cate%"),
			'done_time' => array('between', "$s_t, $e_t")
		);
		$o_result = $this->_order->where($where)->field('sum(`count`) as c, count(id) as cc')->find();
		if($o_result){
			$utwhere = array(
				'type' => array('like', "$cate%"),
				'tiaojian0' => array('elt', $o_result['cc']),
				'tiaojian1' => array('egt', $o_result['cc'])
			);
			$u_list = $utype->where($utwhere)->find();
			if($u_list){
				$count = ($o_result['c'] * $u_list['bili']) / 100;
			}else{
				$count = 0;
			}
		}
		return $count;
	}
	//计算每月最后一天
	public function getLastDay(){
		$BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
		$LastDay = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
		if($LastDay == date('Y-m-d', time())){
			return true;
		}else{
			return false;
		}
	}
	
}